package cn.JHai.rbac.interceptor;

import cn.JHai.rbac.comm.CurrentUtil;
import cn.JHai.rbac.domain.Employee;
import cn.JHai.rbac.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee current = CurrentUtil.getCurrent();
        if (current == null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null)
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("login")) {
                        Employee e = employeeMapper.login(cookie.getValue());
                        CurrentUtil.setCurrent(e);
                        return true;
                    }
                }
            response.sendRedirect("/login.html");
            return false;
        }
        return true;
    }
}
